package com.zry.simpleBlog.comment.config;


import com.zry.simpleBlog.entity.Blog;
import com.zry.simpleBlog.entity.User;
import com.zry.simpleBlog.mapper.BlogMapper;
import com.zry.simpleBlog.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import javax.annotation.Resource;
import java.util.Date;
import java.util.TimeZone;

@Slf4j
@Configuration
public class WebDataInitializer implements InitializingBean {

    @Resource
    private BlogMapper blogMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private Environment env;

    @Value("${init.article.guestbook.id}")
    private String guestbookId;

    @Value("${init.user.id}")
    private String userId;

    private void initUser() {
        User user = userMapper.selectById(userId);
        if (user != null) {
            return;
        }
        user = new User();
        user.setId(userId);
        user.setUsername("root");
        user.setRank(1);
        //root两次加密之后的
        user.setPassword("b5fb686c5752edd1c337ac7231c6cea5");
        user.setNickname("tyux");
        user.setAvatar("/images/avatar/zry.jpg");
        user.setSalt("1a2b3c4d");
        userMapper.insert(user);
        log.info("-------->用户名：root");
        log.info("-------->密码：root");
    }


    private void initBlog() {
        Blog blog = blogMapper.selectById(guestbookId);
        if (blog != null) {
            return;
        }
        blog = new Blog();
        blog.setId(guestbookId);
        blog.setUserId(userId);
        blog.setViews(0L);
        blog.setTitle("留言板");
        blog.setContent("畅所欲言吧");
        blog.setCommentable(true);
        blog.setPublished(false);
        blog.setFlag("原创");
        blog.setCreateTime(new Date());
        blog.setUpdateTime(new Date());
        blogMapper.insert(blog);
    }

    @Override
    public void afterPropertiesSet() {
        log.info("初始化必要数据");
        TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));
        initUser();
        initBlog();
        log.info("必要数据准备完成");

        String port = System.getProperty("server.port") != null ? System.getProperty("server.port") : env.getProperty("server.port");
        String active = System.getProperty("spring.profiles.active") != null ? System.getProperty("spring.profiles.active") : env.getProperty("spring.profiles.active");
        log.info("-------->运行端口：{}", port);
        log.info("-------->运行环境：{}", active);
    }
}
